/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.SecuredAction;
import com.ntb.common.StringUtil;
import com.ntb.controllers.forms.UserForm;
import com.ntb.entities.Users;
import com.ntb.models.UsersDAO;
import com.ntb.models.impl.UsersDAOImpl;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class ProfileAction extends SecuredAction {

    @Override
    public ActionForward ntbExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        List<String> errorMessages = new ArrayList<String>();
        List<String> successMessages = new ArrayList<String>();
        UserForm userForm = (UserForm) form;
        
        if ("Save".equalsIgnoreCase(userForm.getAction()))
        {
            StringUtil stringUtil = new StringUtil();
            String password = stringUtil.generateMD5(userForm.getPassword());
            if (this.currentUser.getPassword().equals(password)) {
                Users user = currentUser;
                user.setEmail(userForm.getEmail());
                user.setFullName(userForm.getFullName());
                user.setGender(userForm.getGender());
                if (userForm.getNewPassword() != null && !"".equals(userForm.getNewPassword())) {
                    user.setPassword(stringUtil.generateMD5(userForm.getNewPassword()));
                }
                UsersDAO userDao = new UsersDAOImpl();
                userDao.update(user);
                successMessages.add("Account Information Successfully Updated.");
            } else {
                errorMessages.add("Wrong password, please try again!");
            }
        }
        
        request.setAttribute("user", this.currentUser);
        userForm.setEmail(this.currentUser.getEmail());
        userForm.setFullName(this.currentUser.getFullName());
        userForm.setGender(this.currentUser.getGender());
        
        request.setAttribute("errorMessages", errorMessages);
        request.setAttribute("successMessages", successMessages);
        
        return mapping.getInputForward();
    }
}
